﻿using DGIS.Control.系统管理;
using DGIS.Model;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Local;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace DGIS.Map.Pages
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        DGIS.Control.GsUserControl _gsUserControl = new Control.GsUserControl();
        private string captchaCode;

        public LoginWindow()
        {
            try
            {
                //实例化CookieContainer
                AppConstant.CookieContainer = new System.Net.CookieContainer();

                InitializeComponent();

                Init();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace + ";" + ex.Message);
            }

        }

        //用户名
        private string _userName;
        //密码
        private string _psw;
        //验证码
        private string _validateCode;

        #region 事件

        //键盘事件
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                AutoLogin_Click(null, null);
        }

        //拖拽
        private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                this.DragMove();
            }
            catch (Exception)
            {

            }
        }

        //关闭
        private void Close_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Environment.Exit(0);
        }

        //登录
        private void Login_Click(object sender, RoutedEventArgs e)
        {
            ShowProgressBar(true);
           
            _validateCode = this.ValidateCode.Text.Trim();

            Task.Run(() =>
            {
                Login();
            }).ContinueWith((x) => { x.Dispose(); });
        }

        private void AutoLogin_Click(object sender, RoutedEventArgs e)
        {
            ShowProgressBar(true);
            _userName ="";
            _psw = "";
            _validateCode = this.ValidateCode.Text.Trim();

            Task.Run(() =>
            {
                Login();
            }).ContinueWith((x) => { x.Dispose(); });
        }


        private void ValidateImg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ChangeValidateCode();
        }

        /// <summary>
        /// 手动更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateTxt_MouseDown(object sender, MouseButtonEventArgs e)
        {
            SysControl sysControl = new SysControl();
            string url = sysControl.CheckSysUpdate();

            if (string.IsNullOrEmpty(url))
            {
                MessageBox.Show("没有检测到新版本");
            }
            else
            {
                Process.Start(url);
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            //清空缓存
            //string cacheFolder = string.Format("{0}Cache",AppDomain.CurrentDomain.BaseDirectory);
            //string[] files = System.IO.Directory.GetFiles(cacheFolder);
            //for (int i = 0; i < files.Length; i++)
            //{
            //    System.IO.File.Delete(files[i]);
            //}

            //显示验证码
            ChangeValidateCode();

            ArcGISRuntime.SetLicense("runtimestandard,101,rud514140042,none,8SF97XLL6S875E5HJ220", new string[] { "runtime3d,101,rud045020986,none,GB2P27E7J34KC2EN0099", "runtimenetwork,101,rud680115591,none,6PB1YPJS3MYPPF002189", "runtimespatial,101,rud274279553,none,0JL400PZAL8M003AD197" });
            ArcGISRuntime.Initialize();

            //加载行政区划
            //string chinaMpkPath = string.Format("{0}Data\\China.mpk", AppDomain.CurrentDomain.BaseDirectory);
            //LocalMapService localMapService = new LocalMapService(chinaMpkPath);
            ////localMapService.StartCompleted += LocalMapService_StartCompleted;
            //localMapService.Start();
        }

        /// <summary>
        /// 更换验证码
        /// </summary>
        private void ChangeValidateCode()
        {
            this.ValidateCode.Clear();
            AppConstant.CookieContainer = new System.Net.CookieContainer();
            Task.Run(() =>
            {
                //获取基本信息
                
                Stream stream = _gsUserControl.GetLoginValidateImg(ref AppConstant.CookieContainer,out captchaCode);
               
                this.ValidateImg.Dispatcher.BeginInvoke(new Action(() =>
                {
                    BitmapImage bitmap = null;
                    if (stream == null)
                    {
                        bitmap = new BitmapImage(new Uri(string.Format("{0}Images//pause.png", AppDomain.CurrentDomain.BaseDirectory)));
                    }
                    else
                    {
                        bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.StreamSource = stream;
                        bitmap.EndInit();
                    }

                    this.ValidateImg.Source = bitmap;

                }));
            }).ContinueWith(x=>x.Dispose());            
        }

        /// <summary>
        /// 验证码检测
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private bool CheackValidate(string code)
        {
            return _gsUserControl.CheackValidate(code, captchaCode, ref AppConstant.CookieContainer);
        }

        /// <summary>
        /// 登录（多线程执行方法）
        /// </summary>
        private void Login()
        {
            GSUser item = null;
            //if (CheackValidate(_validateCode))
            if (true)
            {
                int resultCode;
                item = _gsUserControl.LoginWeb(_userName, _psw, captchaCode, _validateCode.ToUpper(), ref AppConstant.CookieContainer,out resultCode);
                this.Dispatcher.Invoke(new Action(() =>
                {
                    ShowProgressBar(false);

                    switch (resultCode)
                    {
                        case 1:
                            this.Hide();

                            MainWindow frm = new MainWindow(item);
                            frm.Show();
                            break;
                        case -100:
                            ChangeValidateCode();
                            MessageBox.Show("登录失败，您也可以不输入账号密码直接匿名登录");
                            break;
                        case -3:
                            ChangeValidateCode();
                            MessageBox.Show("验证码输入有误");                            
                            break;
                        default:
                            ChangeValidateCode();
                            break;
                    }
                }));
            }

        }

        /// <summary>
        /// 进度条控制
        /// </summary>
        /// <param name="show"></param>
        private void ShowProgressBar(bool show)
        {
            this.ProgressBar.Visibility = show ? Visibility.Visible : Visibility.Hidden;           
        }

        #endregion

        
    }
}
